var repliesSignsURL = "src/services/SignService.php?action=repliesSigns";
var globalSignsURL = "src/services/SignService.php?action=globalSigns";
var mineSignsURL = "src/services/SignService.php?action=mineSigns";
var watchersSignsURL = "src/services/SignService.php?action=watchersSigns";
var profileSignsURL = "src/services/SignService.php?action=profileSigns";
var insertColorfeelChoosedURL = "src/services/SignService.php?action=insertColorfeelChoosed";
var infoMaskerURL = "src/services/MaskerService.php?action=infoMasker";
var countWatcherFromURL = "src/services/WatcherService.php?action=countWatcherFrom";
var countWatcherToURL = "src/services/WatcherService.php?action=countWatcherTo";
var checkFollowURL = "src/services/WatcherService.php?action=checkFollow";
var followUnfollowURL = "src/services/WatcherService.php?action=followUnfollow";
var getWatchersURL = "src/services/WatcherService.php?action=getWatchers";
var getFollowersURL = "src/services/WatcherService.php?action=getFollowers";
var maskerQuestionsURL = "src/services/QuestionService.php?action=maskerQuestions";
var insertQuestionURL = "src/services/QuestionService.php?action=insertQuestion";
var deleteQuestionURL = "src/services/QuestionService.php?action=deleteQuestion";
var updateQuestionAnswerURL = "src/services/QuestionService.php?action=updateQuestionAnswer";

function openSignDetail(obj) {
	openLoading();
	
	//close reply
	$(".sign-detail-reply").hide();
	$(".reply-sign").val("");
	$(".reply-sign-signCharacters").html("250");
	//close replies
	$(".sign-detail-replies").hide();
	//close delete
	
	if($(obj).attr("name_masker") == getNameMasker()) {
		$(".sign-detail-delete").show();
	} else {
		$(".sign-detail-delete").hide();
	}
	
	var page = $(obj).closest(".ui-page").attr("id");
	var selector = "#" + page + " #signDetail";
	
	$(selector + " .sign-detail-message").html($(obj).children(".sign-message").html());
	$(selector + " .sign-detail-color").css("background-color",$(obj).children(".sign-footer").css("background-color"));
	
	$(selector).attr("red",$(obj).attr("red"));
	$(selector).attr("green",$(obj).attr("green"));
	$(selector).attr("blue",$(obj).attr("blue"));
	$(selector).attr("id_sign",$(obj).attr("id_sign"));
	$(selector).attr("name_masker",$(obj).attr("name_masker"));
	
	$(selector).popup("open", {
		positionTo : 'origin'
	});
	
	$("#" + page + " #listDivider").html($(obj).attr("name_masker"));
	closeLoading();
}

function profileSignDetail(obj) {
	openLoading();
	var nameMasker = $(obj).closest(".signDetail").attr("name_masker");
	closeLoading();
	location.href = "#profile?masker=" + nameMasker;
}

function openColorfeel(obj){
	openLoading();
	var page = $(obj).closest(".ui-page").attr("id");
	$("#" + page + " #signDetail").popup("close");
	
	var selector = "#" + page + " #colorfeel";
	
	$(selector + " #red").html(colorfeelNumber(obj.parentNode.parentNode.parentNode.getAttribute("red")));
	$(selector + " #blue").html(colorfeelNumber(obj.parentNode.parentNode.parentNode.getAttribute("blue")));
	$(selector + " #green").html(colorfeelNumber(obj.parentNode.parentNode.parentNode.getAttribute("green")));
	
	$(selector).attr("id_sign", obj.parentNode.parentNode.parentNode.getAttribute("id_sign"));
	
	$(selector).popup("open", {
		positionTo : 'origin'
	});
	closeLoading();
}

function chooseColor(obj, color) {
	openLoading();
	var idSign = $(obj).parent().parent().attr("id_sign");
	var colorToSend = "";
	if (color == "red") {
		$("#sign-"+idSign).attr("red", (Number($("#sign-"+idSign).attr("red")) + 1));
		colorToSend = "r";
	}
	if (color == "green") {
		$("#sign-"+idSign).attr("green", (Number($("#sign-"+idSign).attr("green")) + 1));
		colorToSend = "g";
	}
	if (color == "blue") {
		$("#sign-"+idSign).attr("blue", (Number($("#sign-"+idSign).attr("blue")) + 1));
		colorToSend = "b";
	}
	
	var page = $(obj).closest(".ui-page").attr("id");
	$("#" + page + " #colorfeel").popup("close");
	
	var backgroundColor = colorfeel($("#sign-"+idSign).attr("red"),$("#sign-"+idSign).attr("green"),$("#sign-"+idSign).attr("blue"));
	var totalFeels = Number($("#sign-"+idSign).attr("red")) + Number($("#sign-"+idSign).attr("green")) + Number($("#sign-"+idSign).attr("blue"));
	
	$("#sign-"+idSign).find(".sign-footer").css("background-color", backgroundColor);
	$("#sign-"+idSign).find(".sign-footer-number-total").html(totalFeels);
	
	getJSON($.ajax({
		type : "POST",
		async : false,
		url : insertColorfeelChoosedURL,
		data : {
			sign_id : idSign,
			color : colorToSend,
			id_masker_from : getIdMasker()
		},
		dataType : "JSON"
	})).result;
	
	closeLoading();
}

function insertColorfeelSignDetailLarge(idSign, color) {
	var colorToSend = "";
	if (color == "red") {
		colorToSend = "r";
	}
	if (color == "green") {
		colorToSend = "g";
	}
	if (color == "blue") {
		colorToSend = "b";
	}
	
	$.ajax({
		type : "POST",
		url : insertColorfeelChoosedURL,
		data : {
			sign_id : idSign,
			color : colorToSend,
			id_masker_from : getIdMasker()
		},
		success : function() {
			$(".sign_Detail_larger_box_colorfeel_" + color).html(Number($(".sign_Detail_larger_box_colorfeel_" + color).html()) + 1);
			
			var backgroundColor = colorfeel(
				$(".sign_Detail_larger_box_colorfeel_red").html(),
				$(".sign_Detail_larger_box_colorfeel_green").html(),
				$(".sign_Detail_larger_box_colorfeel_blue").html());
				
			$("#sign-" + idSign + " .sign-footer").css("background-color", backgroundColor);
			$("#sign-" + idSign + " .sign-footer-number-total").html(Number($("#sign-"+idSign+" .sign-footer-number-total").html()) + 1);
		},
		dataType : "JSON"
	});
}

function closeColorfeel() {
	$(".colorfeel").popup("close");
}

function colorfeelNumber(value) {
	return '<div style="padding-top:20px">'+value+'</div>';
}
function getSigns(action, page, append) {
	getSigns(action, page, append, null);
}

function getSigns(action, page, append, idMasker) {
	var lastId = null;
	$(".link-center").hide();
	
	if(append == false) {
		$("#" + page + " #thelist").before(getLoader());
	} else {
		$("#" + page + " #thelist").after(getLoader());
	}
	
	if(append == false) {
		$("#" + page + " #thelist").html("");
		
	}else {
		lastId = $('#'+page+' .sign').last().attr('id_sign');
	}
	
	if (action == "globalSigns") {
		var url = globalSignsURL;
	} else if (action == "mineSigns") {
		var url = mineSignsURL;
	} else if (action == "profileSigns") {
		var url = profileSignsURL;
	} else if (action == "watchersSigns") {
		var url = watchersSignsURL;
	}
	
	$.ajax({
		type : "POST",
		url : url,
		data : {
			id_masker : idMasker,
			last_id : lastId
		},
		success: function(signs) {      
	        for ( index = 0; index < signs.value.length; ++index) {
				$("#" + page + " #thelist").append(createSign(signs.value[index]));;
			}
			
			if (signs.value.length == 0) {
				if (action == "mineSigns") {
					$(".mine_no_sign_found").show();
				} else if (action == "watchersSigns") {
					$(".watchers_no_sign_found").show();
				}
				if(append == true) {
					$(".link-center").hide();
					$(".no_sign_found").hide();
				}
			} else {
				$(".link-center").show();
			}
			
			attachOpenSignDetail();
			
			$(".sign-loader").hide();
			$(".sign-loader").remove();
	   	},
	   	failure: function(e) {
	   		console.log(e);
	   		
			$(".sign-loader").hide();
			$(".sign-loader").remove();
	   	},
		dataType : "JSON"
	});

}

function loadSigns(action, page, append, idMasker){
	getSigns(action, page, append, idMasker);
}

function loadGlobalSigns() {
	loadSigns("globalSigns","global", false);
}

function loadGlobalSignsOlder() {
	loadSigns("globalSigns","global", true);
}

function loadMineSigns(idMasker, append){
	loadSigns("mineSigns","mine", append, idMasker);
}

function loadWatchersSigns(idMasker, append){
	loadSigns("watchersSigns","watchers", append, idMasker);
}

function loadProfileSigns(idMasker, append){
	loadSigns("profileSigns","profile_signs", append, idMasker);
}

function getMaskerInfo(maskerName) {
	return getJSON($.ajax({
		type : "POST",
		async : false,
		url : infoMaskerURL,
		data : {
			name : maskerName
		},
		dataType : "JSON"
	})).result;
}

function countWatcherFrom(idMasker) {
	return getJSON($.ajax({
		type : "POST",
		async : false,
		url : countWatcherFromURL,
		data : {
			id : idMasker
		},
		dataType : "JSON"
	})).result;
}

function countWatcherTo(idMasker) {
	return getJSON($.ajax({
		type : "POST",
		async : false,
		url : countWatcherToURL,
		data : {
			id : idMasker
		},
		dataType : "JSON"
	})).result;
}

// return 2 if is the same masker, 0 not follow, 1 follow
function checkFollow(idMaskerLogged, idMaskerProfile) {
	if(Number(idMaskerLogged) == Number(idMaskerProfile)) {
		return 2;
	} else {
		return getJSON($.ajax({
			type : "POST",
			async : false,
			url : checkFollowURL,
			data : {
				idMaskerLogged : idMaskerLogged,
				idMaskerProfile : idMaskerProfile
			},
			dataType : "JSON"
		})).result.COUNT;
	}
}

// onclick button follow / unfollow a masker
function followUnfollow(maskerName, idMaskerLogged, idMaskerProfile, toFollow) {
	openLoading();
	
	var exec = getJSON($.ajax({
		type : "POST",
		async : false,
		url : followUnfollowURL,
		data : {
			idMaskerLogged : idMaskerLogged,
			idMaskerProfile : idMaskerProfile,
			toFollow : toFollow
		},
		dataType : "JSON"
	})).result;
	
	// reload page
	$(".follow_whatchers_count").html(countWatcherFrom(idMaskerProfile).COUNT);
	$(".have_whatchers_count").html(countWatcherTo(idMaskerProfile).COUNT);
	
	var checkFollowValue = checkFollow(idMaskerLogged, idMaskerProfile);
	
	if(checkFollowValue == 2) {
		$(".followUnfollow_unfollow").hide();
		$(".followUnfollow_follow").hide();
	} else if(checkFollowValue == 1) {
		$(".followUnfollow_follow").hide();
		$(".followUnfollow_unfollow").show();
	} else if(checkFollowValue == 0) {	
		$(".followUnfollow_unfollow").hide();
		$(".followUnfollow_follow").show();
	}
			
	closeLoading();
}


function profile(idMasker) {
	$("#profile_found").hide();
	
	$("#profile_loader").html(getLoader());
	$("#profile_loader").show();
	
	// clean values
	$(".profile_name").html("");
	$(".profile_total_sign_count").html("");
	$(".profile_total_sign_love_count").html("");
	$(".profile_total_sign_question_count").html("");
	$(".follow_whatchers_count").html("");
	$(".have_whatchers_count").html("");
	
	//profile_total_sign_question_count
	//profile_total_achievement_count
	
	$(".follow_whatchers_count").html(0);
	$(".have_whatchers_count").html(0);
	
	if (getUrlVars()["masker"] != null) {
		maskerProfile = getMaskerInfo(getUrlVars()["masker"]);
		if(maskerProfile != null) {
			$(".profile_name").html(maskerProfile.name);
			$(".profile_total_sign_question_count").html(maskerProfile.question_count);
			$(".profile_total_sign_count").html(maskerProfile.sign_count);
			$(".profile_total_sign_love_count").html(maskerProfile.colorfeel_count);
			
			//profile_total_sign_question_count
			//profile_total_achievement_count
			
			$(".follow_whatchers_count").html(countWatcherFrom(maskerProfile.id).COUNT);
			$(".have_whatchers_count").html(countWatcherTo(maskerProfile.id).COUNT);
			
			// if is anonymous, no question!
			if(maskerProfile.id == 0) {
				$(".profile_question_element").hide();
				$(".watcher_box").hide();
			} else {
				$(".profile_question_element").show();
				$(".watcher_box").show();
			}
			
			var checkFollowValue = checkFollow(idMasker, maskerProfile.id);
			
			if(checkFollowValue == 2 || idMasker == 0) {// if anonym, can't follow/unfollow people
				$(".followUnfollow_unfollow").hide();
				$(".followUnfollow_follow").hide();
			} else if(checkFollowValue == 1) {
				$(".followUnfollow_follow").hide();
				$(".followUnfollow_unfollow").show();
			} else if(checkFollowValue == 0) {	
				$(".followUnfollow_unfollow").hide();
				$(".followUnfollow_follow").show();
			}
			
			$(".profile_sign_element").click(function() {
			    loadProfileSignList(maskerProfile.id,maskerProfile.name);
			});
			$(".profile_question_element").click(function() {
			    loadProfileQuestionList(maskerProfile.name);
			});
			$("#profile_loader").hide();
			$("#profile_found").show();
		} else {
			setMessage("profile.not.found",".profile_name");
			$("#profile_loader").hide();
			$("#profile_found").hide();
		}
	}
}

function loadProfileSignList(maskerId, maskerName){
	location.href = "#profile_signs?masker=" + maskerId + "&maskerName=" + maskerName;
}

function loadProfileQuestionList(maskerName){
	location.href = "#questions?masker=" + maskerName;
}

function manageLink(page){
	$(".footerLinks").removeClass("ui-btn-active");
	$("."+ page).addClass("ui-btn-active");
}

function followers(nameMasker) {
	return getJSON($.ajax({
		type : "POST",
		async : false,
		url : getFollowersURL,
		data : {
			name : nameMasker
		},
		dataType : "JSON"
	})).result;
}

function watchers(nameMasker) {
	return getJSON($.ajax({
		type : "POST",
		async : false,
		url : getWatchersURL,
		data : {
			name : nameMasker
		},
		dataType : "JSON"
	})).result;
}

function watchers_followers(w_f) {
	openLoading();
	var isWatchers = (w_f == "watchers");
		
	setMessage("profile.back.to.profile",".back_to_profile");
	
	maskerName = getUrlVars()["masker"];
	if (maskerName != null) {
		if (isWatchers) {
			var target = getMessage("profile.watchers");
			var maskerList = watchers(maskerName);
			var targetUL = ".ul_masker_list_watchers";
		} else {
			var target = getMessage("profile.followers");
			var maskerList = followers(maskerName);
			var targetUL = ".ul_masker_list_followers";
		}
		$(".profile_name").html(maskerName + " " + target);
		
		var code = "";
		for ( index = 0; index < maskerList.length; ++index) {
			code += "<li class=\"li_masker_list\" onclick=\"goto('home.php#profile?masker="+maskerList[index].name+"')\">"+maskerList[index].name+"</li>";
		}
		
		if (maskerList == null || maskerList.length == 0) {
			code += "<li class=\"li_masker_list\">"+getMessage("profile.no.watcher.found")+"</li>";
		}
		
		$(targetUL).html(code);
	} else {
		setMessage("profile.not.found",".profile_name");
	}
	
	closeLoading();
}

function openReply(obj) {
	var reply = $(obj).closest(".signDetail").find(".sign-detail-reply");
	if (reply.is(':visible')) {
		reply.hide();
	} else {
		reply.show();
	}
}

function deleteSignDetail(obj) {
	var idSign = $(obj).closest(".signDetail").attr("id_sign");
	var idMasker = getIdMasker();
	var result =  deleteSign(idSign, idMasker);
	closeSignDetail(obj);
	return result;
}

function openReplies(obj) {
	var replies = $(obj).closest(".signDetail").find(".sign-detail-replies");
	var idSign = $(obj).closest(".signDetail").attr("id_sign");
	if (replies.is(':visible')) {
		replies.hide();
	} else {
		replies.show();
		var code = "";
		$(".sign-detail-replies-ul").html("<li class=\"sign-detail-replies-li-noreplies\">"+"<img src=\"images/loader.gif\">"+"</li>");

		var signs = getJSON($.ajax({
			type : "POST",
			async : false,
			url : repliesSignsURL,
			data : {
				id_sign_father : idSign
			},
			dataType : "JSON"
		})).value;
		
		if(signs.length == 0) {
			code ="<li class=\"sign-detail-replies-li-noreplies\">"+getMessage("sign.detail.replies.no.replies")+"</li>";
		} else {
			for(var i=0; i < signs.length; i++) {
				code += "<li class=\"sign-detail-replies-li\">"+createSign(signs[i])+"</li>";
			}
		}
		
		$(".sign-detail-replies-ul").html(code);
		attachOpenSignDetail();
	}
	
}

function openSignDetailLarge(obj) {
	var idSign = $(obj).closest(".signDetail").attr("id_sign");
	location.href = "#signDetailLarge?id=" + idSign;
}

function attachOpenSignDetail() {
	$(".sign").click(function(){
		openSignDetail(this);
   	});
}

function loadProfileQuestions(maskerNameLogged){
		openLoading();
		$(".questions-ul").html("<li class=\"question-li-noquestions\">"+"<img src=\"images/loader.gif\">"+"</li>");
		maskerName = getUrlVars()["masker"];
		var title = "";
		if (maskerName != null){
			if (maskerNameLogged != maskerName && maskerName != "anonymous") {
				$(".new-question-box").show();
			} else {
				$(".new-question-box").hide();
			}
			title = maskerName;
			
			var questions = getJSON($.ajax({
				type : "POST",
				async : false,
				url : maskerQuestionsURL,
				data : {
					masker : maskerName
				},
				dataType : "JSON"
			})).value;
			
			var code = "";
			if(questions.length == 0 || maskerName == "anonymous") {
				code ="<li class=\"question-li-noquestions\">"+getMessage("questions.no.questions")+"</li>";
			} else {
				for(var i=0; i < questions.length; i++) {
					code += createQuestion(questions[i]);
				}
			}
			$(".questions-ul").html(code);
			// open detail question only for the owner of the question
			if (maskerNameLogged == maskerName && maskerNameLogged != "") {
				$(".question-li-element").click(function(question) {
			    	openQuestionDetail(question);
				});
			}
		}else {
			$(".new-question-box").hide();
			title = getMessage("questions.profile.not.found");
		}
		title = title + " " + getMessage("questions.title");
		$(".profile_name").html(title);
		
		closeLoading();
	}

function popupErrors(message) {
	$('.errorPopup #errorMessage').html(message);
		closeLoading();
		$(".errorPopup").popup();
		$(".errorPopup").popup('open');
		return false;
}

function insertQuestion(nameMaskerTo, idMaskerFrom, nameMaskerFrom, idSign, targetText) {
	openLoading();
	var textValue = $(targetText).val();
	if(textValue == "") {
		popupErrors(getMessage("question.not.empty"));
		return false;
	}
	if(textValue.length > 500) {
		popupErrors(getMessage("question.too.long"));
		return false;
	}
	var result = getJSON($.ajax({
		type : "POST",
		async : false,
		url : insertQuestionURL,
		data : {
			id_masker_from : idMaskerFrom,
			name_masker_to : nameMaskerTo,
			text : textValue
		},
		dataType : "JSON"
	})).result;
	setColorCounter(500,".questionCharacters");
	$(targetText).val("");
	closeLoading();
	loadProfileQuestions(nameMaskerFrom);
	return result;
}

function openQuestionDetail(question) {
	var idQuestion = $(question.currentTarget).attr("idquestion");
	//var answer = $("li[idquestion="+idQuestion+"]").find(".question-message-answer").html();
	//$("#new-question-answer").val(answer);
	$(".questionDetail").attr("idquestion",idQuestion);
	$(".questionDetail").popup("open", {
		positionTo : 'origin'
	});
}
function closeQuestionDetail() {
	$(".questionDetail").popup("close");
}

function openAnswerDiv() {
	var answerDiv = $(".question_detail_answer_box");
	if (answerDiv.is(':visible')) {
		answerDiv.hide();
	} else {
		answerDiv.show();
	}
}

function updateQuestionAnswer(nameMaskerTo, idMasker, targetText) {
	openLoading();
	var idQuestion = $(".questionDetail").attr("idquestion");
	var text_answer = $(targetText).val();
	if(text_answer == "") {
		popupErrors(getMessage("question.not.empty"));
		return false;
	}
	if(text_answer.length > 500) {
		popupErrors(getMessage("question.too.long"));
		return false;
	}
	var result = getJSON($.ajax({
		type : "POST",
		async : false,
		url : updateQuestionAnswerURL,
		data : {
			id_masker : idMasker,
			id_question : idQuestion,
			text_answer : text_answer
		},
		dataType : "JSON"
	})).result;
	$(".questionDetail").popup("close");
	setColorCounter(500,".questionCharacters");
	$(targetText).val("");
	closeLoading();
	loadProfileQuestions(nameMaskerTo);
	return result;
}

function deleteQuestion(nameMaskerTo, idMasker, obj) {
	if(!confirm(getMessage("question.delete.are.you.sure"))){
		return false;
	}
	openLoading();
	var idQuestion = $(".questionDetail").attr("idquestion");
	var result = getJSON($.ajax({
		type : "POST",
		async : false,
		url : deleteQuestionURL,
		data : {
			id_masker : idMasker,
			id_question : idQuestion
		},
		dataType : "JSON"
	})).result;
	$(".questionDetail").popup("close");
	closeLoading();
	loadProfileQuestions(nameMaskerTo);
	return result;
}

//TODO fare shorturl per sign

